<?php

class wechatController extends RPHP_Controller
{

    //oauth
    public function oauth()
    {
        $m = $this->model;    
        $wechat       = $m->getWeixinSetting();
        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/wechat/callback';
        $state        = 'wechat';
        $scope        = 'snsapi_userinfo';
        $oauth_url    = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $wechat['appid'] . '&redirect_uri=' . urlencode($redirect_uri) . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';

        $this->redirect($oauth_url);
    }

    //callback
    public function callback()
    {

        $m            = $this->model;
        $data['code'] = 900;

        if ($_GET['code'] != "" && preg_match("/^([0-9a-zA-Z]{30,64})$/", $_GET['code'])) {
            $wechat = $m->getWeixinSetting();
            //get oauth access_token
            $url           = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $wechat['appid'] . '&secret=' . $wechat['appsecret'] . '&code=' . $_GET['code'] . '&grant_type=authorization_code';
            $json_tmp_data = @file_get_contents($url);
            $json          = json_decode($json_tmp_data, true);

            if ($json['openid'] != "" && $json['access_token'] != "") {
                // get userinfo
                $url           = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $json['access_token'] . '&openid=' . $json['openid'] . '&lang=zh_CN';
                $user_tmp_data = @file_get_contents($url);
                $user          = json_decode($user_tmp_data, true);
                if ($user['unionid'] != "" || $user['openid'] != "") {
                    
                    $data = $m->checkWechatUser($user);

                    if ($_SESSION['HTTP_REFERER'] != "") {

                        $refurl = Rfc::decode($_SESSION['HTTP_REFERER']);

                    } else {

                        $refurl = "/";
                    }

                    // 登录成功，且不用完善手机号码
                    if ($data['code'] == 200) {

                        $this->redirect($refurl);

                    }
                    // 需要完善手机号码
                    elseif ($data['code'] == 501) {
                        $refurl = "/user/update_account?type=mobile&a=m&ref=" . Rfc::encode($refurl);
                        $this->redirect($refurl);
                    }

                } else {
                    $data['code'] = 404;
                }

            }

        }

        if ($data['code'] != 200 && $data['code'] != 501) {
            echo "WECHAT AUTH FAILED. ERRORCODE:" . $data['code'];
        }

    }

}
